using System.Security.Claims;

namespace HtERP.Services;

/// <summary>
/// 认证服务接口
/// </summary>
public interface IAuthService
{
    /// <summary>
    /// 用户登录
    /// </summary>
    /// <param name="username">用户名</param>
    /// <param name="password">密码</param>
    /// <param name="saveCredentials">是否保存凭据以供后续自动登录使用</param>
    /// <returns>登录结果</returns>
    Task<LoginResult> LoginAsync(string username, string password, bool saveCredentials = false);
    
    /// <summary>
    /// 用户注销
    /// </summary>
    /// <returns>注销结果</returns>
    Task LogoutAsync();
    
    /// <summary>
    /// 获取当前用户信息
    /// </summary>
    /// <returns>当前用户信息</returns>
    Task<CurrentUser> GetCurrentUserAsync();
    
    /// <summary>
    /// 检查用户是否已登录
    /// </summary>
    /// <returns>是否已登录</returns>
    Task<bool> IsAuthenticatedAsync();
    
    /// <summary>
    /// 检查用户是否具有指定角色
    /// </summary>
    /// <param name="role">角色名称</param>
    /// <returns>是否具有该角色</returns>
    Task<bool> IsInRoleAsync(string role);
    
    /// <summary>
    /// 检查用户是否已登录（别名方法）
    /// </summary>
    /// <returns>是否已登录</returns>
    Task<bool> IsLoggedInAsync() => IsAuthenticatedAsync();
    
    /// <summary>
    /// 使用保存的凭据登录
    /// </summary>
    /// <returns>登录结果</returns>
    Task<LoginResult> LoginWithSavedCredentialsAsync();
    
    /// <summary>
    /// 获取认证令牌
    /// </summary>
    /// <returns>认证令牌</returns>
    string GetAuthToken();

    /// <summary>
    /// 获取或刷新WebAPI认证令牌（仅用于文件上传等需要WebAPI访问的功能）
    /// </summary>
    /// <returns>认证令牌</returns>
    Task<string> GetOrRefreshAuthTokenAsync();

    /// <summary>
    /// 保存用户凭据以供后续自动登录使用
    /// </summary>
    /// <param name="username">用户名</param>
    /// <param name="password">密码</param>
    /// <returns>是否保存成功</returns>
    Task<bool> SaveCredentialsAsync(string username, string password);
}

/// <summary>
/// 登录结果类
/// </summary>
public class LoginResult
{
    /// <summary>
    /// 是否登录成功
    /// </summary>
    public bool Success { get; set; }
    
    /// <summary>
    /// 错误信息
    /// </summary>
    public string ErrorMessage { get; set; } = string.Empty;
    
    /// <summary>
    /// 用户声明
    /// </summary>
    public IEnumerable<Claim> Claims { get; set; } = Enumerable.Empty<Claim>();
}

/// <summary>
/// 当前用户信息类
/// </summary>
public class CurrentUser
{
    /// <summary>
    /// 用户ID
    /// </summary>
    public string UserId { get; set; } = string.Empty;
    
    /// <summary>
    /// 用户名
    /// </summary>
    public string Username { get; set; } = string.Empty;
    
    /// <summary>
    /// 用户角色
    /// </summary>
    public List<string> Roles { get; set; } = new List<string>();
    
    /// <summary>
    /// 是否已登录
    /// </summary>
    public bool IsAuthenticated { get; set; }
    
    /// <summary>
    /// 错误消息
    /// </summary>
    public string ErrorMessage { get; set; } = string.Empty;
}